/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.mem.impl.disk;

import java.io.IOException;

import org.sabayframework.activity.ActivityContext;
import org.sabayframework.activity.impl.TimerActivity;
import org.sabayframework.channel.Channel;
import org.sabayframework.channel.impl.NullChannel;
import org.sabayframework.channel.ram.ArrayChannel;
import org.sabayframework.mem.BigBuffer;
import org.sabayframework.mem.IdGenerator;
import org.sabayframework.mem.MemException;
import org.sabayframework.mem.Memorizable;
import org.sabayframework.mem.Transaction;
import org.sabayframework.mem.Transaction.Locking;
import org.sabayframework.mem.cache.Cache;
import org.sabayframework.mem.cache.CacheFactory;
import org.sabayframework.mem.impl.AbstractSpace;
import org.sabayframework.mem.impl.SequentialIdGenerator;
import org.sabayframework.mem.impl.TransactionImpl;
import org.sabayframework.queue.ExecutionQueue;

/**
 * Implementation of Space that keeps data on a disk storage.
 * @author Alex Antonau
 * */
public class DiskSpace extends AbstractSpace {
	
	private final DiskStorageImpl storage;
	private static final long COMPACT_PERIOD=1000*60;
	
	private final CacheFactory<Memorizable> cacheFactory;
	private final Cache<BigBuffer> cache;
	
	
	class Compacter extends TimerActivity<Object, Object>{
		public Compacter() {
			super(COMPACT_PERIOD, COMPACT_PERIOD);
		}
		@Override
		public void scheduledRun(ActivityContext<Object, Object> ctx) throws Exception {
			storage.compact();
		}
		@Override
		public boolean isDone(ActivityContext<Object, Object> ctx) throws Exception {
			if(isClosed()) return true;
			return super.isDone(ctx);
		}
	}
	
	public DiskSpace(String workPath, ExecutionQueue executionQueue, Cache<BigBuffer> readCache, CacheFactory<Memorizable> cacheFactory) throws IOException {
		this(workPath, new SequentialIdGenerator(0), executionQueue, readCache, cacheFactory);
	}
	/**
	 * @param readCache shared read cache
	 * @param cacheFactory cache factory for transaction caches
	 * */
	public DiskSpace(String workPath, IdGenerator idGenerator, ExecutionQueue executionQueue,
			Cache<BigBuffer> readCache, CacheFactory<Memorizable> cacheFactory) throws IOException {
		super(idGenerator, executionQueue);
	
		this.storage = new DiskStorageImpl(workPath);
		this.cache = readCache;
		this.cacheFactory = cacheFactory;
		executionQueue.submit(new Compacter(), NullChannel.getInstance(), NullChannel.getInstance());
	}

	public DiskStorage getStorage() {
		return storage;
	}

	public CacheFactory<Memorizable> getCacheFactory() {
		return cacheFactory;
	}
	public Cache<BigBuffer> getCache() {
		return cache;
	}
	public Channel<Long> getNumberOfRecords() {
		ArrayChannel<Long> res = new ArrayChannel<Long>(1);
		try{
			res.add(storage.getNumberOfRecords());
		}catch (Throwable e) {
			res.fail(e);
		}
		return res;
	}

	public Channel<Long> getFreeBytes() {
		ArrayChannel<Long> res = new ArrayChannel<Long>(1);
		try{
			res.add(storage.getFreeSpace());
		}catch (Throwable e) {
			res.fail(e);
		}
		return res;
	}

	public Channel<Long> getUsedBytes() {
		ArrayChannel<Long> res = new ArrayChannel<Long>(1);
		try{
			res.add(storage.getUsedSpace());
		}catch (Throwable e) {
			res.fail(e);
		}
		return res;
	}

	@Override
	public Transaction beginTransaction(Locking locking) {
		if(isClosed()) throw new IllegalStateException("Space is closed");
		final TransactionImpl t = new TransactionImpl(getIdGenerator().getNextId(), getExecutionQueue());
		try{
		switch (locking) {
		case NONE:
			t.submitProcessingActivity(new NoLockTxActivity(t, this));
			break;
		case OPTIMISTIC:
		case PESSIMISTIC:
			t.submitProcessingActivity(new PessimisticTxActivity(t, this));
			break;
		default:
			throw new IllegalArgumentException("Unsupported locking: "+locking);
		}
		} catch (IOException e) {
			throw new MemException(e);
		}
		started(t);
		return t;
	}

	@Override
	public void close() throws IOException {
		super.close();
		storage.close();
	}

	public void delete() throws IOException{
		if(!isClosed()) close();
		storage.delete();
	}

}
